﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;

namespace DevGridViewDragDropTest
{
    public class User {
        public int Id {set;get;}
        public string Name { set; get; }
        public int Age { set; get; }
        public string Add { set; get; }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SetDtSource();

         

            GridViewInit();
            BindGrid();
            DragHelper.DragGridRow<DataRowView>(this.gridView1);
            //DragHelper.DragGridRow<User>(this.gridView1);
        }
        //鼠标坐标
        private GridHitInfo downHitInfo; //鼠标左键按下去时在GridView中的坐标
        private GridHitInfo upHitInfo; //鼠标左键弹起来时在GridView中的坐标
        private int startRow; // 拖拽的第一行
        private int[] rows; //拖拽的所有行
        //数据源
        DataTable dtSource;


        private void SetDtSource1()
        {
            List<User> lstUser = new List<User>();
            for (int i = 0; i < 20; i++)
            {
                User user = new User();
                lstUser.Add(user);
                user.Id = i;
                if (i % 2 == 1)
                {
                    user.Name = "小张" + i;
                    user.Age = 20 + i;
                }
                else
                {
                    user.Name = "老李" + i;
                    user.Age = 10 + i;
                }
                user.Add = "陕西省西安市第" + i + "大道";
            }
            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = lstUser;
            gridControl1.DataSource = bindingSource;
        }


        private void SetDtSource()
        {
            dtSource = new DataTable();
            dtSource.Columns.Add("id", typeof(int));
            dtSource.Columns.Add("name", typeof(string));
            dtSource.Columns.Add("age", typeof(int));
            dtSource.Columns.Add("add", typeof(string));
            DataRow dr;
            for (int i = 0; i < 20; i++)
            {
                dr = dtSource.NewRow();
                dr["id"] = i;
                if (i % 2 == 1)
                {
                    dr["name"] = "小张" + i;
                    dr["age"] = 20 + i;
                }
                else
                {
                    dr["name"] = "老李" + i;
                    dr["age"] = 10 + i;
                }
                dr["add"] = "陕西省西安市第" + i + "大道";
                dtSource.Rows.Add(dr);
            }
            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = dtSource;
            gridControl1.DataSource = bindingSource;

        }
        private void GridViewInit()
        {
            gridControl1.AllowDrop = true; // 确保能够拖拽
            //gridView1.OptionsSelection.MultiSelect = false;   //确保能够多选
            //gridView1.OptionsSelection.EnableAppearanceFocusedCell = false; //确保选定行的背景色一样
            //gridView1.OptionsSelection.EnableAppearanceFocusedCell = false; //确保选定行的背景色一样。
            gridView1.OptionsBehavior.Editable = false;
        }
        private void BindGrid()
        {
           
        }

        //鼠标按下事件
        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            downHitInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));   //鼠标左键按下去时在GridView中的坐标
        }

        //鼠标移动事件
        private void gridView1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;        //不是左键则无效
            if (downHitInfo == null || downHitInfo.RowHandle < 0) return;   //判断鼠标的位置是否有效

            rows = gridView1.GetSelectedRows();  //获取所选行的index
            startRow = rows.Length == 0 ? -1 : rows[0];
            DataTable dt = dtSource.Clone();

            foreach (int r in rows)   // 根据所选行的index进行取值，去除所选的行数据，可能是选取的多行
            {
                int dataSourcerows = gridView1.GetDataSourceRowIndex(r); //获取行数据
                dt.ImportRow(dtSource.Rows[dataSourcerows]); //保存所选取的行数据
            }
           gridControl1.DoDragDrop(dt, DragDropEffects.Move);//开始拖放操作，将拖拽的数据存储起来
        }

        //拖拽过程事件
        private void gridControl1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        //拖拽完成后事件
        private void gridControl1_DragDrop(object sender, DragEventArgs e)
        {
            Point gridviewPoint = this.PointToScreen(this.gridControl1.Location);  //获取鼠标在屏幕上的位置。
            upHitInfo = gridView1.CalcHitInfo(new Point(e.X - gridviewPoint.X, e.Y - gridviewPoint.Y));   //鼠标左键弹起来时在GridView中的坐标（屏幕位置减去 gridView 开始位置）
            if (upHitInfo == null || upHitInfo.RowHandle < 0) return;

            int endRow = gridView1.GetDataSourceRowIndex(gridView1.GetDataSourceRowIndex(upHitInfo.RowHandle)); //获取拖拽的目标行index

            DataTable dt = e.Data.GetData(typeof(DataTable)) as DataTable;  //获取要移动的数据，从拖拽保存的地方：（gridControl1.DoDragDrop(dt, DragDropEffects.Move); ）

            if (dt != null && dt.Rows.Count > 0) //拖拽的数据为空
            {
                int a;
                DataRow xs = dtSource.Rows[endRow]; //获取拖拽的目标行，准备进行移植
                if (!rows.Contains(endRow))  //如果多选的话，确保不能拖拽到这几个里
                {
                    gridView1.ClearSelection();  //从GirdView中删除所拖拽的数据
                    int moveValue = 0;
                    foreach (int i in rows)
                    {
                        dtSource.Rows.Remove(dtSource.Rows[i - moveValue]);  //从GirdView的数据源中删除所拖拽的数据
                        moveValue++;
                    }

                    if (startRow > endRow)
                        a = dtSource.Rows.IndexOf(xs);  //若果往上托，则加在鼠标到达行的上面
                    else
                        a = dtSource.Rows.IndexOf(xs) + 1;  //如果往下拖，则加在鼠标到达行的下面
                    int j = 0;
                    DataRow drTemp;
                    foreach (DataRow dr in dt.Rows)
                    {
                        drTemp = dtSource.NewRow();
                        foreach (DataColumn dc in dr.Table.Columns)
                        {
                            drTemp[dc.ColumnName] = dr[dc.ColumnName];
                        }
                        dtSource.Rows.InsertAt(drTemp, a + j); //将拖拽的数据再次添加进来
                        gridView1.SelectRow(a + j);
                        j++;
                    }
                    gridView1.FocusedRowHandle = a;
                }
                gridControl1.DataSource = dtSource; //重新绑定
                gridView1.RefreshData();
            }
        }
    }
}
